package com.kb.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisPlusConfig {
    //忽略租户过滤表集合
    @Value("${ignore-tenant-tables:}")
    private String ignoreTenantTables;

    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        if (!StringUtils.isBlank(ignoreTenantTables)) {
            List<String> ignoreTenantTableList = Arrays.asList(StringUtils.split(ignoreTenantTables, ","));
//            if (!CollectionUtils.isEmpty(ignoreTenantTableList)) {
                TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(new TenantLineHandler() {
                    @Override
                    public Expression getTenantId() {
                        return new LongValue(1);
                    }
                    @Override
                    public String getTenantIdColumn() {
                        return "tenant_id";
                    }
                    @Override
                    public boolean ignoreTable(String tableName) {
                        //这是我的一个上下文类，忽略当前线程使用租户数据隔离 具体要忽略的表到yml文件配置
                        if (CollectionUtils.isEmpty(ignoreTenantTableList)) {
                            return false;
                        }
                        return ignoreTenantTableList.contains(tableName);
                    }
                });
                //开启多租户模式
//                interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
//            }
//        }

        //分页插件
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setMaxLimit(-1L);
//        paginationInterceptor.setDbType(DbType.MYSQL);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setOptimizeJoin(true);

        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }

}
